package com.GlobalPaint.app.ui.Mine.Personal;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.GlobalPaint.app.Base.DialogWaiting;
import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.EventBusben;
import com.GlobalPaint.app.bean.LogBean;
import com.GlobalPaint.app.bean.PersonalBean;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.bean.codeBean;
import com.GlobalPaint.app.bean.postxinxiBean;
import com.GlobalPaint.app.bean.pusbTouxiang;
import com.GlobalPaint.app.listener.UILPauseOnScrollListener;
import com.GlobalPaint.app.ui.MainActivity;
import com.GlobalPaint.app.utils.CommUtility;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.GlobalPaint.app.utils.SiliCompressor;
import com.GlobalPaint.app.utils.UILImageLoader;
import com.blankj.utilcode.utils.FileUtils;
import com.blankj.utilcode.utils.SPUtils;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.google.gson.Gson;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import de.hdodenhof.circleimageview.CircleImageView;

public class PersonalActivity extends AppCompatActivity implements View.OnClickListener {
    private final int REQUEST_CODE_CAMERA = 1000;
    private final int REQUEST_CODE_GALLERY = 1001;
    private List<PhotoInfo> mDatas = new ArrayList<>();
    private CircleImageView imge_touxiang;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.ed_qq)
    EditText edQq;
    @BindView(R.id.ed_weixin)
    EditText edWeixin;
    @BindView(R.id.ed_MSN)
    EditText edMSN;
    @BindView(R.id.et_company)
    EditText etCompany;
    @BindView(R.id.et_jianjie)
    EditText etJianjie;
    private ImageView iv_goback;
    private TextView tv_common_center;
    private RelativeLayout rl_sex;
    private TextView sex;
    private TextView common;
    private PersonalBean personalBean;
    private Dialog dlgWaiting2;
    private String file1;
    private codeBean codebean;
    private pusbTouxiang pusbtouxiang;
    private String xingbie;
    private LogBean logBean;
    private SPUtils spUtils;
    private postxinxiBean sendsmsBean;
    String fNickName1;
    private  String main;  //跳转页面参数
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal);
        ButterKnife.bind(this);
        spUtils = new SPUtils(DataManager.context, "login");
        main=getIntent().getStringExtra("main");
        initView();
        getInformation();
    }

    private void getInformation() {
            dlgWaiting2 = DialogWaiting.createDialogWaiting(PersonalActivity.this, "加载中......");
            dlgWaiting2.show();
            String url= Constants.JASON_SERVICE_URL+"user/getUserById?userid="+ DataManager.userEntity.getUserId();
            DataManager.getInst().getHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), PersonalBean.class, new DataManager.Callback() {
                @Override
                public void onSuccess(Object o) {
                    dlgWaiting2.cancel();
                    personalBean=(PersonalBean)o;
                    if (personalBean.getStatus() == 1){
                        if(personalBean.getData() != null ){
                            String qq = personalBean.getData().getFQq() ==
                                    null ? "" : personalBean.getData().getFQq();
                            String Weixin = personalBean.getData().getFWeixin() ==
                                    null ? "" : personalBean.getData().getFWeixin();
                            String Msn = personalBean.getData().getFNickName() ==
                                    null ? "" : personalBean.getData().getFNickName();
                            String Company = personalBean.getData().getCompany() ==
                                    null ? "" : personalBean.getData().getCompany();
                            String Bio = personalBean.getData().getFBio() ==
                                    null ? "" : personalBean.getData().getFBio();
                            String Gender = personalBean.getData().getFGender() ==
                                    null ? "" : personalBean.getData().getFGender();
                            String Url= personalBean.getData().getAvatar()== null?"wu":
                                    personalBean.getData().getAvatar();
                            if(Url.equals("wu")){
                                Picasso.with(PersonalActivity.this).load(R.drawable.touxiang).into(imge_touxiang);
                            }else {
                                Picasso.with(PersonalActivity.this)
                                        .load(Constants.JASON_SERVICE_URL_TOUXIANG+Url)
                                        .memoryPolicy(MemoryPolicy.NO_CACHE)

                                        .networkPolicy(NetworkPolicy.NO_CACHE)
                                        .placeholder(R.drawable.touxiang).into(imge_touxiang);
                            }
                            edQq.setText(qq);
                            edWeixin.setText(Weixin);
                            edMSN.setText(Msn);
                            etCompany.setText(Company);
                            etJianjie.setText(Bio);
                            if(Gender.equals("M")){
                                sex.setText("男");
                            }else {
                                sex.setText("女");
                            }

                        }
                    }
                    else {
                        Toast.makeText(PersonalActivity.this,personalBean.getMsg(),Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure(ReturnStatusResultEntity error) {
                }
            });
            dlgWaiting2.cancel();
    }

    private void initView() {
        imge_touxiang = (CircleImageView)findViewById(R.id.imge_touxiang);
        imge_touxiang.setOnClickListener(this);
        iv_goback = (ImageView) findViewById(R.id.iv_goback);
        iv_goback.setOnClickListener(this);
        tv_common_center = (TextView) findViewById(R.id.tv_common_center);
        tv_common_center.setText("个人信息");
        rl_sex = (RelativeLayout) findViewById(R.id.rl_sex);
        rl_sex.setOnClickListener(this);
        sex = (TextView) findViewById(R.id.sex);
        if (DataManager.userEntity.getUserName()!=null){
            String Phone =DataManager.userEntity.getUserName();
            if (Phone.length() > 4) {
                String phone1 = (Phone.substring(0, 3));
                String phone2 = Phone.substring(Phone.length() - 3, Phone.length());
                tvName.setText(phone1 + "***" + phone2);
            }
        }
        common = (TextView) findViewById(R.id.common);
        common.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imge_touxiang:
                selectImg();
                break;
            case R.id.rl_sex:
                getSex();
                break;
            case R.id.iv_goback:
                finish();
                break;
            case R.id.common:
                getCommit();
                break;
        }

    }

    private void getCommit() {
        if (sex.getText().equals("男")) {
            xingbie="M";
        } else {
            xingbie="F";
        }
        final String fNickName=edMSN.getText().toString();
        if(TextUtils.isEmpty(fNickName)){
            Toast.makeText(PersonalActivity.this, "请输入昵称", Toast.LENGTH_LONG).show();
            return;
        }


     /*   if(edWeixin.getText().toString()!=null){

            if(CommUtility.isEmail(edWeixin.getText().toString())==false){
                Toast.makeText(PersonalActivity.this, "请输入正确的邮箱格式", Toast.LENGTH_LONG).show();
                return;
            }

        }*/
        try {
            fNickName1 = URLEncoder.encode(URLEncoder.encode(fNickName, "utf-8"), "utf-8");
        }catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String fBio=etJianjie.getText().toString();
        String fQq=edQq.getText().toString();
        String fWeixin=edWeixin.getText().toString();

        String company=etCompany.getText().toString();
        String  posturl = Constants.JASON_SERVICE_URL+ "user/editAppUser?fUserId="+DataManager.userEntity.getUserId()
              +"&fUsername="+DataManager.userEntity.getUserName()+"&fBio="+etJianjie.getText().toString()
              +"&fQq="+edQq.getText().toString() +"&fWeixin="+edWeixin.getText().toString()
              +"&fNickName="+fNickName+"&company="+etCompany.getText().toString()
              +"&fGender="+xingbie;
        Log.d("mainActivity", "url2==" +posturl);
        DataManager.getInst().getHttpRequestJsonClass(posturl, DataManager.userEntity.getCookie(),PersonalBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                personalBean = (PersonalBean) o;
                if(personalBean.getStatus()==1){
                    DataManager.userEntity.setfNickName(fNickName);
                    spUtils = new SPUtils(DataManager.context, "login");
                    spUtils.putString("user", new Gson().toJson( DataManager.userEntity));
                    spUtils.putString("login",fNickName);
                    Toast.makeText(PersonalActivity.this, "修改成功", Toast.LENGTH_LONG).show();
                    Intent Intent1=new Intent();
                    Intent1.putExtra("ddd",edMSN.getText().toString());
                    setResult(RESULT_OK,Intent1);
                    if (main.equals("main")){
                        Intent intent=new Intent(PersonalActivity.this, MainActivity.class);
                        startActivity(intent);
                    }
                    finish();
                }else {
                    Toast.makeText(PersonalActivity.this, personalBean.getMsg(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {
                Toast.makeText(PersonalActivity.this, "修改失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void getSex() {
        final String[] mlist = new String[]{"男", "女"};
        final ActionSheetDialog dialog = new ActionSheetDialog(PersonalActivity.this, mlist, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                sex.setText(mlist[position]);

                dialog.dismiss();
            }
        });
    }
    //打开相册
    private void selectImg() {
        mDatas.clear();
        ThemeConfig theme = new ThemeConfig.Builder()
                .build();
        //配置功能
        final FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(false)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(true)
                .setSelected(mDatas)
                .setMutiSelectMaxSize(1)
//                .setFilter(mList)
                .build();
        CoreConfig coreConfig = new CoreConfig.Builder(PersonalActivity.this, new UILImageLoader(), theme)
                .setFunctionConfig(functionConfig)
                .setPauseOnScrollListener(new UILPauseOnScrollListener(false, true))
                .build();
        GalleryFinal.init(coreConfig);
        String[] function = new String[]{"打开相册", "拍照"};
        final ActionSheetDialog dialog = new ActionSheetDialog(PersonalActivity.this, function, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY, functionConfig, mOnHanlderResultCallback);
                        break;
                    case 1:
                        GalleryFinal.openCamera(REQUEST_CODE_CAMERA, functionConfig, mOnHanlderResultCallback);
                        break;
                    default:
                        break;
                }
                dialog.dismiss();
            }
        });
    }
    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (resultList != null) {

                for (PhotoInfo result : resultList) {
                    boolean exists = false;
                    for (PhotoInfo photoInfo : mDatas) {
                        if (TextUtils.equals(photoInfo.getPhotoPath(), result.getPhotoPath())) {
                            exists = true;
                            break;
                        }
                    }
                    if (!exists) {
                        boolean deal = CommUtility.dealRotateImage(result.getPhotoPath());
                        mDatas.add(result);
                    }
                }
                if (FileUtils.isFileExists(resultList.get(0).getPhotoPath())) {

                      /* String filePath = SiliCompressor.with(getApplicationContext()).compress(mDatas.get(0).getPhotoPath());
                       ImageLoader.getInstance().displayImage(filePath,imge_touxiang);*/
                    try {
                        imge_touxiang.setImageBitmap(SiliCompressor.with(PersonalActivity.this).getCompressBitmap(mDatas.get(0).getPhotoPath()));
                        file1=SiliCompressor.with(PersonalActivity.this).compress(mDatas.get(0).getPhotoPath());
                        File file=new File(file1);
                   /*     pusbtouxiang=new pusbTouxiang();
                        pusbtouxiang.setFile(file);
                        pusbtouxiang.setfUserId(DataManager.userEntity.getUserId());
                        pusbtouxiang.setfUsername(DataManager.userEntity.getUserName());*/

                        putimge(file);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            CommUtility.ShowMsgShort(PersonalActivity.this, errorMsg);
        }
    };

    private void putimge(File file) {
        String url =Constants.JASON_SERVICE_URL + "user/editAppUserImage?fUserName="
                +DataManager.userEntity.getUserName()+"&fUserId="+DataManager.userEntity.getUserId();
        DataManager.getInst().postHttpRequesFileClass(url, DataManager.userEntity.getCookie(), file,codeBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                codebean=(codeBean) o;
                if (codebean.getStatus()==1){
                    EventBusben baseMessage = new EventBusben("touxiang");
                    EventBus.getDefault().post(baseMessage);
                  /*  DataManager.userEntity.setAvatar(logBean.getData().getAvatar());
                    spUtils.putString("user", new Gson().toJson(DataManager.userEntity));*/
                }
            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {

            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
